package com.mall.shopping.redis;

import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 设置Redis为MyBatis二级缓存
 * @author xiaofan
 * @version 1.0
 */
public class RedisCache implements Cache {
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private final String id; // cache instance id
    private RedisTemplate redisTemplate; //可以理解为他是一个中间件连接redis和mybatis二级缓存
    private static final long EXPIRE_TIME_IN_MINUTES = 30; // redis过期时间

    public RedisCache(String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        this.id = id;
    }

    /**
     * 获取id
     * @return String id值
     */
    @Override
    public String getId() {
        return id;
    }

    /**
     * 向缓存中放入查询结果
     * @param key 键
     * @param value 值
     */
    @Override
    @SuppressWarnings("unchecked")
    public void putObject(Object key, Object value) {
        getRedisTemplate().opsForValue().setIfAbsent(key.toString(), value, EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES);
        System.out.println("--- 放入结果到缓存 ---");
    }

    /**
     * 从缓存中获取查询结果
     * @param key 键
     * @return Object
     */
    @Override
    public Object getObject(Object key) {
        System.out.println("--- 获取结果从缓存 ---");
        return getRedisTemplate().opsForValue().get(key.toString());
    }

    /**
     * 移除redis中cache的查询结果
     * @param key 键
     * @return Object
     */
    @Override
    @SuppressWarnings("unchecked")
    public Object removeObject(Object key) {
        System.out.println("--- 从缓存删除了 ---");
        return getRedisTemplate().boundHashOps(getId()).delete(key);
    }

    /**
     * 清除缓存实例
     * <p>MyBatis二级缓存 只要有update insert delete均会清空缓存</p>
     * <p>因此二级缓存适合多查少改的数据</p>
     * <p>这里因为后台的每步操作均要写入日志，因此LogMapper取消了二级缓存</p>
     */
    @Override
    public void clear() {
        RedisTemplate redisTemplate = getRedisTemplate();
        redisTemplate.execute((RedisCallback) connection -> {
            connection.flushDb();
            return null;
        });
        System.out.println("--- 清缓存 ---");
    }

    /**
     * 获取缓存大小
     * @return int
     */
    @Override
    public int getSize() {
        Long size = getRedisTemplate().boundHashOps(getId()).size();
        return size == null ? 0 : size.intValue();
    }

    /**
     * 设置读写锁
     *  重写这个方法之后 读读不互斥,读写互斥,写写互斥
     * @return ReadWriteLock
     */
    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }

    /**
     * 获取Redis RedisTemplate
     * @return RedisTemplate
     */
    private RedisTemplate getRedisTemplate() {
        if (redisTemplate == null) {
            redisTemplate = SpringContextHolder.getBean("redisTemplate");
        }
        return redisTemplate;
    }
}